//
//  AppDelegate.m
//  AiYue
//
//  Created by mac on 2023/10/9.
//

#import "AppDelegate.h"
#import "IQKeyboardManager.h"
#import "AY_GenderViewController.h"
#import <BUAdSDK/BUAdSDK.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/AdSupport.h>
#import "AY_SplashAd.h"
#import <BUAdSDK/BUAdSDK.h>
#import <AVFoundation/AVFoundation.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/ASIdentifierManager.h>
#if __has_include(<BUAdTestMeasurement/BUAdTestMeasurement.h>)
#import <BUAdTestMeasurement/BUAdTestMeasurement.h>
#endif
#import "AY_SplashViewController.h"
#import "AY_BookShelfViewController.h"
@interface AppDelegate ()
@property (nonatomic, strong) AY_SplashAd *splashAd;
@property (nonatomic, strong) AY_SplashViewController *splashVC;
@property (nonatomic, strong) UIWindow *launchWindow;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [MMKV initializeMMKV:nil];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    self.mainTab = [[AY_MainTabViewController alloc] init];
    UINavigationController *nav = [UINavigationController rootVC:self.mainTab translationScale:NO];
    self.window.rootViewController = nav;
    [self setKeyboard];
    //[self.window makeKeyAndVisible];
    
    
    self.launchWindow = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.splashVC = [[AY_SplashViewController alloc]init];
    self.launchWindow.backgroundColor = [UIColor whiteColor];
    self.launchWindow.rootViewController = self.splashVC;
    [self.launchWindow makeKeyAndVisible];
    // initialize AD SDK
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self requestIDFA];
    });
    return YES;
}

- (void)getConfigInfo {
    [AYApiRequest APPConfigSuccess:^(AY_ConfigModel * _Nonnull pkg) {
        [AYMMKV setString:pkg.data.ap forKey:AP];
        [AYMMKV setString:pkg.data.wx forKey:WX];
        [AYMMKV setString:pkg.data.kt forKey:KT];
        [AYMMKV setString:pkg.data.zf forKey:ZF];
        [AYMMKV setString:pkg.data.zfb forKey:ZFB];
        [AYMMKV setString:pkg.data.wxStr forKey:WXSTR];
        [AYMMKV setString:pkg.data.cz forKey:CZ];
        [AYMMKV setString:pkg.data.gm forKey:GM];
        [AYMMKV setString:pkg.data.invite_friend_desc forKey:INVITEFIREND];
    } failure:^(int status, NSString * _Nonnull info) {
    }];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[NSNotificationCenter defaultCenter] postNotificationName:ZFREFRESH object:nil];
    [AYAPP registerUser];
    [self getIsEditData];
    [self getConfigInfo];
}

- (void)getIsEditData {
    [AYApiRequest getIsEditSuccess:^(AY_IsEditModel * _Nonnull pkg) {
        if ([pkg.data isEqual:@"1"]) {
            [AYMMKV setBool:YES forKey:ISSHENHE];
        }else {
            [AYMMKV setBool:NO forKey:ISSHENHE];
        }
        if ([AYMMKV getBoolForKey:ISFIRST defaultValue:YES]) {
            AY_GenderViewController *genVC = [[AY_GenderViewController alloc] init];
            self.window.rootViewController = genVC;
        }else {
            //if ([AYMMKV getBoolForKey:ISSHENHE]) {
//                self.mainTab = [[AY_MainTabViewController alloc] init];
//                UINavigationController *nav = [UINavigationController rootVC:self.mainTab translationScale:NO];
//                self.window.rootViewController = nav;
//            }
        }
    } failure:^(int status, NSString * _Nonnull info) {
        [AYMMKV setBool:YES forKey:ISSHENHE];
        if ([AYMMKV getBoolForKey:ISFIRST defaultValue:YES]) {
            AY_GenderViewController *genVC = [[AY_GenderViewController alloc] init];
            self.window.rootViewController = genVC;
        }else {
            self.mainTab = [[AY_MainTabViewController alloc] init];
            UINavigationController *nav = [UINavigationController rootVC:self.mainTab translationScale:NO];
            self.window.rootViewController = nav;
        }
//        self.mainTab = [[AY_MainTabViewController alloc] init];
//        UINavigationController *nav = [UINavigationController rootVC:self.mainTab translationScale:NO];
//        self.window.rootViewController = nav;

//        AY_IsEditMainViewController *genVC = [[AY_IsEditMainViewController alloc] init];
//        UINavigationController *nav = [UINavigationController rootVC:genVC translationScale:NO];
//        self.window.rootViewController = nav;
    }];
}

- (void)setKeyboard {
    IQKeyboardManager.sharedManager.enable = YES;
    IQKeyboardManager.sharedManager.enableAutoToolbar = YES;
    IQKeyboardManager.sharedManager.shouldResignOnTouchOutside = YES;
    IQKeyboardManager.sharedManager.keyboardDistanceFromTextField = 0;
    [IQKeyboardManager sharedManager].toolbarDoneBarButtonItemText = @"完成";
}

- (void)setupBUAdSDK {
#if __has_include(<BUAdTestMeasurement/BUAdTestMeasurement.h>)
#if DEBUG
    // 测试工具
    [BUAdTestMeasurementConfiguration configuration].debugMode = YES;
#endif
#endif
    BUAdSDKConfiguration *configuration = [BUAdSDKConfiguration configuration];
    configuration.appID = @"5658049";
    // 设置日志输出
    configuration.debugLog = @(1);
    // 设置使用聚合
    configuration.useMediation = YES;
    // 隐私合规配置
    // 是否禁止CAID
    configuration.mediation.forbiddenCAID = @(0);
    // 是否限制个性化广告
    configuration.mediation.limitPersonalAds = @(0);
    // 是否限制程序化广告
    configuration.mediation.limitProgrammaticAds = @(0);
    // 主题模式
    configuration.themeStatus = @(BUAdSDKThemeStatus_Normal);
    // 本地配置路径 ** 请检查配置路径是否正确 **
    //    NSString *advanceSDKConfigPath = [[NSBundle mainBundle] pathForResource:@"GroMore-config-ios-202502192051.json" ofType:nil];
    //    configuration.mediation.advanceSDKConfigPath = advanceSDKConfigPath;
    //[self useMediationSettings];
    Weak_Self;
    if (![AYMMKV getBoolForKey:ISSHENHE defaultValue:YES]) {
            [BUAdSDKManager startWithAsyncCompletionHandler:^(BOOL success, NSError *error) {
                if (success) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // 开屏广告
                        [self.splashAd p_buildAdandWithCloseAdBlock:^{
                            // 关闭
                            [[NSNotificationCenter defaultCenter] postNotificationName:REFRECommend object:nil];
                            [weakSelf.window makeKeyAndVisible];
                        } andWithLoadSuccessBlock:^{
                                weakSelf.isShowAd = YES;
                                [[NSNotificationCenter defaultCenter] postNotificationName:REFRECommend object:nil];
                                [weakSelf.window makeKeyAndVisible];
                            
                        }];
                    });
                }else{
                    [[NSNotificationCenter defaultCenter] postNotificationName:REFRECommend object:nil];
                    [weakSelf.window makeKeyAndVisible];
                }
            }];
    
            }else{
                weakSelf.isShowAd = YES;
                [weakSelf.splashAd.splashAd showSplashViewInRootViewController:weakSelf.window.rootViewController];
                [weakSelf.window makeKeyAndVisible];

            }
    
//    [BUAdSDKManager startWithAsyncCompletionHandler:^(BOOL success, NSError *error) {
//        if (success) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                // 开屏广告
//                [self.splashAd p_buildAdandWithCloseAdBlock:^{
//                    // 关闭
//                    [[NSNotificationCenter defaultCenter] postNotificationName:REFRECommend object:nil];
//                    [weakSelf.window makeKeyAndVisible];
//                } andWithLoadSuccessBlock:^{
//                    if ([AYMMKV getBoolForKey:ISSHENHE defaultValue:YES]) {
//                        weakSelf.isShowAd = YES;
//                        [[NSNotificationCenter defaultCenter] postNotificationName:REFRECommend object:nil];
//                        [weakSelf.window makeKeyAndVisible];
//                    }else{
//                        weakSelf.isShowAd = YES;
//                        [weakSelf.splashAd.splashAd showSplashViewInRootViewController:weakSelf.window.rootViewController];
//                        [weakSelf.window makeKeyAndVisible];
//
//                    }
//                }];
//            });
//        }else{
//            [[NSNotificationCenter defaultCenter] postNotificationName:REFRECommend object:nil];
//            [weakSelf.window makeKeyAndVisible];
//        }
//    }];
    
    
//    if (![AYMMKV getBoolForKey:ISSHENHE defaultValue:YES]) {
//        [BUAdSDKManager startWithAsyncCompletionHandler:^(BOOL success, NSError *error) {
//            if (success) {
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self.splashAd p_buildAdandWithCloseAdBlock:^{
//                        // 关闭
//                        [[NSNotificationCenter defaultCenter] postNotificationName:REFRECommend object:nil];
//                        [weakSelf.window makeKeyAndVisible];
//                    } andWithLoadSuccessBlock:^{
//                        weakSelf.isShowAd = YES;
//                        [weakSelf.splashAd.splashAd showSplashViewInRootViewController:weakSelf.window.rootViewController];
//                        [weakSelf.window makeKeyAndVisible];
//                    }];
//                });
//            }else{
//                [[NSNotificationCenter defaultCenter] postNotificationName:REFRECommend object:nil];
//                [weakSelf.window makeKeyAndVisible];
//            }
//        }];
//    }
    
    
    
}

- (void)requestIDFA {
    if (@available(iOS 14, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            //  授权完成回调
            [self setupBUAdSDK ];
        }];
    } else {
        [self setupBUAdSDK ];
    }
}


// 关于使用聚合功能的相关设置
- (void)useMediationSettings {
    BUAdSDKConfiguration *configuration = [BUAdSDKConfiguration configuration];
    // 聚合流量分组
    BUMUserInfoForSegment *segment = [[BUMUserInfoForSegment alloc] init];
    segment.user_id = @"Please enter your user's Id";
    segment.user_value_group = @"group1";
    segment.age = 19;
    segment.gender = BUUserInfoGenderMale;
    segment.channel = @"Apple";
    segment.sub_channel = @"Apple store";
    configuration.mediation.userInfoForSegment = segment;
    // 隐私合规
    configuration.mediation.limitPersonalAds = @(0);
    configuration.mediation.limitProgrammaticAds = @(0);
    configuration.mediation.forbiddenCAID = @(0);
}


- (AY_SplashAd *)splashAd {
    if (!_splashAd) {
        _splashAd = [AY_SplashAd new];
    }
    return _splashAd;
}
@end
